package dwz.cms.article.impl;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import dwz.cms.article.common.Constants;
import dwz.cms.article.common.HtmlUtil;
import dwz.cms.article.util.ftp.FTPUtils;
import dwz.cms.article.util.ftp.MyFTPFile;
import dwz.persistence.beans.Article;
import dwz.persistence.beans.CmsChannel;
import dwz.persistence.beans.CmsResource;
import dwz.persistence.beans.SysStaticconnection;
import dwz.persistence.mapper.ArticleMapper;
import dwz.persistence.mapper.CmsArtChannelMapper;
import dwz.persistence.mapper.CmsArticleDraftMapper;
import dwz.persistence.mapper.CmsChannelMapper;
import dwz.persistence.mapper.CmsResourceMapper;
import dwz.persistence.mapper.SysStaticconnectionMapper;

/**
 * Created by Eclipse
 * 
 * @author : Yating
 * @version:2017年5月8日 上午10:34:22 类说明
 */
@Service("sysStaticconnectionService")
public class SysStaticconnectionService {

	@Autowired
	private IArticleDisp articleDispService;

	@Resource
	CmsArticleDraftMapper cmsArticleDraftMapper;

	@Resource
	CmsArtChannelMapper cmsArtChannelMapper;

	@Resource
	ArticleMapper articleMapper;

	@Resource
	CmsChannelMapper cmsChannelMapper;
	
	@Resource
	SysStaticconnectionMapper sysStaticconnectionDao;
	@Resource
	CmsResourceMapper cmsResourceDao;
	
	private JdbcTemplate jdbcTemplate;
	private String pageURL = Constants.JSEEA_HALF_STATIC_ADDRESS;
	private String fileName = null;
	private String fileRoot = Constants.CMS_STATIC_ROOT + "Static/";
	private Vector<MyFTPFile> files = new Vector<MyFTPFile>();
	private String operation = FTPUtils.UPLOAD;

	public Vector<MyFTPFile> buildWholeSite() {
		// files = new Vector<MyFTPFile>();
		// List<Map> channels = jdbcTemplate
		// .queryForList("select id from cms_channel");

		files = new Vector<MyFTPFile>();
		List<CmsChannel> channels = cmsChannelMapper.selectChannelList();

		if (channels.size() < 1)
			return files;

		for (CmsChannel channel : channels) {
			Integer channelId = (Integer) channel.getId();
			buildStaticPages(channelId);
		}
		return files;
		// sysStaticconnectionDao.findByHql("");
	}

	/**
	 * 更新并上传整个频道的文章
	 * 
	 * @param channelId
	 */
	public Vector<MyFTPFile> buildStaticPages(Integer channelId) {
		// List<Article> art = sysStaticconnectionDao
		// .findByHql("select p from CmsArtChannel ac, NoContentPublish p where
		// ac.code=p.code and ac.channelid="
		// + channelId);

		List<Article> art = articleDispService.getArticleByChannelId(channelId);
		if (art.size() < 1)
			return files;
		return buildStaticPages(art, channelId);

	}

	public Vector<MyFTPFile> buildStaticPages(List<Article> articleList) {

		for (Article article : articleList) {
			String code = article.getCode();
			Date date = article.getCreatetime();

			if (code.isEmpty() || date == null)
				continue;

			// 根据文章的code获取文章存在的channelids
			// List<Map> channelids = jdbcTemplate.queryForList(
			// "select channelid from cms_art_channel where code=?",
			// new Object[] { article.getCode() });

			// 根据文章的code获取文章存在的channelids
			List<String> channelids = cmsArtChannelMapper.selectChannelListByCode(code);
			if (channelids.size() < 0)
				continue;
			for (String strChannelId : channelids) {
				Integer channelId = Integer.parseInt(strChannelId);
				// buildStaticPages(articleList, channelId);
				buildStaticPages(code, date, channelId);
			}
		}
		return files;
	}

	public Vector<MyFTPFile> buildStaticPages(List<Article> articleList, Integer channelId) {
		for (Article article : articleList) {
			String code = article.getCode();
			Date date = article.getCreatetime();
			buildStaticPages(code, date, channelId);
		}
		return files;
		// HtmlUtil.upLoadFiles(files);
	}

	public Vector<MyFTPFile> buildStaticPages(String code, Date date) {
		if (code.isEmpty() || date == null)
			return files;
		// List<Map> channelids = jdbcTemplate.queryForList(
		// "select channelid from cms_art_channel where code=?",
		// new Object[] { code });

		// 根据文章的code获取文章存在的channelids
		List<String> channelids = cmsArtChannelMapper.selectChannelListByCode(code);
		
		if (channelids.size() < 0)
			return files;
		for (String  strChannelId : channelids) {
			Integer channelId = Integer.parseInt(strChannelId);;
			buildStaticPages(code, date, channelId);
		}
		return files;
	}

	public Vector<MyFTPFile> buildStaticPages(String code, Date date, Integer channelId) {
		if (code.isEmpty() || channelId == null || date == null)
			return files;
		List<SysStaticconnection> allSysStatList=null;
		try {
			allSysStatList = sysStaticconnectionDao.selectSysStaticconnectionByChannelId(Integer.valueOf(channelId));
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		for (SysStaticconnection sc : allSysStatList) {
			switch (sc.getFreshtype()) {
			case 1:// page 页面
					// /contents/channel_<%=channelid%>/09/01/code.html
				pageURL = Constants.JSEEA_HALF_STATIC_ADDRESS + sc.getFreshhtml() + code;
				String currentPath = "contents/channel_" + channelId + "/" + HtmlUtil.generateFilePath(date);
				String goalPath = fileRoot + currentPath;
				fileName = code + Constants.EXT_HTM;

				MyFTPFile file = new MyFTPFile(new File(goalPath, fileName), currentPath, operation);
				// System.out.println(currentPath);
				if (!files.contains(file)) {
					files.add(file);
					if (operation.equals(FTPUtils.UPLOAD))
						HtmlUtil.buildStaticPage(pageURL, goalPath, fileName);
				}
				//List<CmsResource> resList =cmsResourceDao. cmsResourceDao.findByHql("from CmsResource where code='" + code + "'");
				// 根据文章code获取文章对应的资源信息
				List<CmsResource> resList =cmsResourceDao.selectCmsResourceByCode(code);
				
				if (resList.size() > 0) {
					for (CmsResource cmsResource : resList) {
						if (cmsResource.getKind() == 6) {
							if (cmsResource.getPath().startsWith("Category1")) {
								String imgPath = cmsResource.getPath();
								imgPath = imgPath.substring(imgPath.lastIndexOf("/") + 1) + "/";
								file = new MyFTPFile(new File(fileRoot + cmsResource.getPath(), cmsResource.getName()),
										currentPath + imgPath, operation);
								if (!files.contains(file)) {
									files.add(file);

								}
							} else {
								file = new MyFTPFile(new File(fileRoot + cmsResource.getPath(), cmsResource.getName()),
										currentPath, operation);
								if (!files.contains(file))
									files.add(file);
							}
						} else {
							file = new MyFTPFile(new File(fileRoot + cmsResource.getPath(), cmsResource.getName()),
									cmsResource.getPath(), operation);
							if (!files.contains(file))
								files.add(file);
						}
					}
				}

				break;
			case 2:// list 页面

//				int count = jdbcTemplate.queryForInt("select count(*) from cms_art_channel where channelid=?",
//						new Object[] { channelId });

				int count = cmsArtChannelMapper.getArticleNumByChannelid(channelId);
				
				int pagenum = 0;
				// 2015新增手机迁移版分页以每页显示11条
				if (channelId == 188 || channelId == 187 || channelId == 189 || channelId == 190 || channelId == 191
						|| channelId == 192) {
					if (count % 11 == 0) {
						pagenum = count / 11;
					} else {
						pagenum = count / 11 + 1;
					}

				} else {
					if (count % Constants.pageSize == 0) {
						pagenum = count / Constants.pageSize;
					} else {
						pagenum = count / Constants.pageSize + 1;
					}
				}
				// ---新增代码结束
				// 源代码，由于和上面新增代码重复，故注释
				// if (count % Constants.pageSize == 0) {
				// pagenum = count / Constants.pageSize;
				// } else {
				// pagenum = count / Constants.pageSize + 1;
				// }
				//
				goalPath = fileRoot + HtmlUtil.generateFilePath(date);
				String webPath = findWebPath(channelId);
				if (webPath == null) {
					break;
				}
				webPath = webPath.replace("/", "");
				for (int i = 1; i <= pagenum; i++) {
					pageURL = Constants.JSEEA_HALF_STATIC_ADDRESS + sc.getFreshhtml() + i;
					currentPath = webPath + "/";
					goalPath = fileRoot + currentPath;
					fileName = sc.getTargetname() + "_" + i + Constants.EXT_HTM;

					file = new MyFTPFile(new File(goalPath, fileName), currentPath, FTPUtils.UPLOAD);
					if (!files.contains(file)) {
						files.add(file);
						HtmlUtil.buildStaticPage(pageURL, goalPath, fileName);
					}
				}

				break;
			case 3:// 首页及其子首页

				pageURL = Constants.JSEEA_HALF_STATIC_ADDRESS + sc.getFreshhtml();
				fileName = sc.getTargetname() + Constants.EXT_HTM;

				file = new MyFTPFile(new File(fileRoot, fileName), ".", FTPUtils.UPLOAD);
				if (!files.contains(file)) {
					HtmlUtil.buildStaticPage(pageURL, fileRoot, fileName);
					files.add(file);
				}
				break;
			default:
				break;
			}
		}
		return files;
	}

	public String findWebPath(Integer channelId) {
//		List<Map> list = jdbcTemplate.queryForList("select webpath from cms_channel where id=" + channelId);
		
		List<String> list = cmsChannelMapper.selectWebpathBychannelid(channelId);		
		
//		return (String) (list.size() > 0 ? list.get(0).get("webpath") : null);
		
		return (String) (list.size() > 0 ? list.get(0) : null);
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public String getFileRoot() {
		return fileRoot;
	}

	public void setFileRoot(String fileRoot) {
		this.fileRoot = fileRoot;
	}

	public void setCmsResourceDao(CmsResourceMapper cmsResourceDao) {
		this.cmsResourceDao = cmsResourceDao;
	}

	public void setSysStaticconnectionDao(SysStaticconnectionMapper sysStaticconnectionDao) {
		this.sysStaticconnectionDao = sysStaticconnectionDao;
	}

	public Vector<MyFTPFile> getFiles() {
		return files;
	}

	public void setFiles(Vector<MyFTPFile> files) {
		this.files = files;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

}
